package com.zeros.mysplashtwo.presenter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.zeros.mysplashtwo.base.BasePresenter;
import com.zeros.mysplashtwo.bean.AdMessageBean;
import com.zeros.mysplashtwo.bean.LoginCheckBean;
import com.zeros.mysplashtwo.http.MyRxSubscribe;
import com.zeros.mysplashtwo.model.LauncherModelImp;
import com.zeros.mysplashtwo.utils.Constants;
import com.zeros.mysplashtwo.utils.SPUtilsTwo;
import com.zeros.mysplashtwo.utils.ZlogUtilTwo;
import com.zeros.mysplashtwo.view.contract.LauncherContract;
import com.zhy.autolayout.utils.L;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * LauncherPresenter(广告)实现类 on 2017/12/21.
 * 需要包含model（处理数据，如下载）、
 * 与 View（展现数据）
 */

public class LauncherPresenterImpl extends BasePresenter<LauncherContract.View> {

    private LauncherModelImp mAdModel;

    public LauncherPresenterImpl() {
        mAdModel = new LauncherModelImp();
    }

    /**
     * 1. 向服务器请求是否要播放广告
     */
    public void getLoginCheck() {
        mAdModel.getLoginCheck()
                .subscribeOn(Schedulers.io())   //发布者在后台线程中运行
                .observeOn(AndroidSchedulers.mainThread())  //订阅者在Android主线程中运行
//                1.此处用的是Observer
                .subscribe(new Observer<LoginCheckBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(LoginCheckBean loginCheckBean) {
                        getMyView().setLoginCheckBean(loginCheckBean);
                        if (loginCheckBean.isPlayAd()) {
                            //这里需要添加一个是否已经下载的判断，如果已经下载，则不再进行下载
                            getAdMessage();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ZlogUtilTwo.e(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        ZlogUtilTwo.e("-----------Complete--------------");
                    }
                });
    }

    // 这里需要添加一个是否已经下载的判断，如果已经下载，则不再进行下载
    private void getAdMessage() {
        mAdModel.getAdMessage()
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                // 2.此处用的是Consumer
                .subscribe(new Consumer<AdMessageBean>() {
                    @Override
                    public void accept(AdMessageBean adMessageBean) throws Exception {
                        getMyView().setLauncherTime(adMessageBean.getAdTime());
                        getAdPicture(adMessageBean.getAdPictureUrl(), "123.jpg");//如果没有下载，直接下载
                    }
                });
    }

    // 获取要展示的广告图片
    private void getAdPicture(final String fileUrl, final String fileName) {
        if (SPUtilsTwo.get((Context) getMyView(), Constants.ADPICURL_KEY, "").equals(fileUrl)) {
            ZlogUtilTwo.e("------从本地获取图片");
            getLocalPicture((String) SPUtilsTwo.get((Context) getMyView(), Constants.ADPICADDRESS_KEY, ""));

        } else {
            ZlogUtilTwo.e("----从网络中获取图片");
            mAdModel.downLoadFile(fileUrl)
                    .subscribeOn(Schedulers.newThread())  //发布者在后台线程中运行
                    .observeOn(AndroidSchedulers.mainThread())    //订阅者在Android主线程中运行
                    .map(new Function<ResponseBody, Bitmap>() {
                        @Override
                        public Bitmap apply(ResponseBody responseBody) throws Exception {
                            if (responseBody != null) {
                                ZlogUtilTwo.e("收到的responseBody不为空！");
                            }
                            if (writeResponseBodyToDisk(responseBody, fileName, fileUrl)) {
                                Bitmap bitmap = BitmapFactory.decodeFile(((Context) getMyView())
                                        .getExternalFilesDir(null) + File.separator + fileName);
                                return bitmap;
                            }
                            return null;
                        }
                    })
                    // 3.此处用的是自定义MyRxSubscribe
                    .subscribe(new MyRxSubscribe<Bitmap>((Context) getMyView()) {
                        @Override
                        protected void _onNext(Bitmap bitmap) {
                            getMyView().setLauncherImg(bitmap);
                        }

                        @Override
                        protected void _onError(String message) {

                        }
                    });
        }
    }


    //从本地获取图片
    private void getLocalPicture(String localUrl) {
        Bitmap bitmap = BitmapFactory.decodeFile(localUrl);
        getMyView().setLauncherImg(bitmap);
    }


    //从网络获取图片并写进内存
    private boolean writeResponseBodyToDisk(ResponseBody body, String fileName, String fileUrl) {
        try {
            // todo change the file location/name according to your needs
            File iconfile = new File(((Context) getMyView()).getExternalFilesDir(null)
                    + File.separator + fileName);
            ZlogUtilTwo.e("文件的保存地址为：" + ((Context) getMyView()).getExternalFilesDir(null) + File.separator + fileName);
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[1024 * 4];
                long fileSize = body.contentLength();
                long fileDownload = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(iconfile);

                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileDownload += read;

                    ZlogUtilTwo.e("file download: " + fileDownload / fileSize * 100);
                    ZlogUtilTwo.e("file download: " + fileDownload + " of " + fileSize);
                }

                outputStream.flush();

                SPUtilsTwo.put((Context) getMyView(), Constants.ADPICADDRESS_KEY, ((Context) getMyView()).getExternalFilesDir(null) + File.separator + fileName);
                SPUtilsTwo.put((Context) getMyView(), Constants.ADPICURL_KEY, fileUrl);
                return true;

            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }


}
